package com.systemservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.systemservice.mapper.LoginMapper;
import com.systemservice.mapper.RoleMapper;
import com.systemservice.mapper.UserInfoMapper;
import com.systemservice.service.LoginService;
import generator.domain.Login;
import generator.domain.Role;
import generator.domain.UserInfo;
import generator.support.ResponseResult;
import generator.vo.LoUsRo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.RandomStringUtils;
import util.MD5Util;

import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author 杨健康
* @description 针对表【t_login】的数据库操作Service实现
* @createDate 2022-06-15 16:07:40
*/
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login>
    implements LoginService {

    @Autowired
    LoginMapper loginMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserInfoMapper userInfoMapper;

    /**
     * 获取所有账户信息
     */
    @Override
    public List<Map<String, Object>> getAllLogin() {
        QueryWrapper<Login> loginQueryWrapper = new QueryWrapper<>();
        List<Login> logins = loginMapper.selectList(loginQueryWrapper);
        List<Map<String, Object>> result = new ArrayList<>();
        GetInfoByLogin(result, logins);
        return result;
    }

    /**
     * 模糊查询账户信息
     */
    @Override
    public List<Map<String, Object>> likeLogin(Login login) {
        List<Map<String, Object>> result = new ArrayList<>();
        QueryWrapper<Login> loginQw = new QueryWrapper<>();
        if (!"".equals(login.getUserAccount()) && login.getUserAccount() != null){
            loginQw.eq("user_account", login.getUserAccount());
        }
        if (login.getUserStatus() != null && login.getUserStatus() != -1){
            loginQw.eq("user_status", login.getUserStatus());
        }
        if (login.getUserRoleId() != null && login.getUserRoleId() != -1){
            loginQw.eq("user_role_id", login.getUserRoleId());
        }
        List<Login> logins = loginMapper.selectList(loginQw);
        GetInfoByLogin(result, logins);
        return result;
    }

    /**
     * 从Login表中提取出role和userInfo信息
     */
    private void GetInfoByLogin(List<Map<String, Object>> result, List<Login> logins) {
        for (Login loginTemp : logins) {
            Map<String, Object> map = new HashMap<>();
            map.put("login", loginTemp);
            // 获取角色信息
            QueryWrapper<Role> roleQw = new QueryWrapper<>();
            roleQw.eq("role_id", loginTemp.getUserRoleId());
            List<Role> roles = roleMapper.selectList(roleQw);
            if (!roles.isEmpty()){
                map.put("role", roles.get(0));
            } else {
                Role temp = new Role();
                temp.setRoleName("该身份已被删除");
                map.put("role", temp);
            }
            // 获取员工信息
            QueryWrapper<UserInfo> userQw = new QueryWrapper<>();
            userQw.eq("user_info_id", loginTemp.getUserNo());
            List<UserInfo> userInfos = userInfoMapper.selectList(userQw);
            if (!userInfos.isEmpty()){
                map.put("userInfo", userInfos.get(0));
            } else {
                UserInfo temp = new UserInfo();
                temp.setUserName("该员工已被删除");
                map.put("userInfo", temp);
            }
            result.add(map);
        }
    }

    /**
     * 添加账户
     */
    @Override
    public ResponseResult<Object> addNewLogin(LoUsRo loUsRo){
        Login login = loUsRo.getLogin();
        UserInfo userInfo = loUsRo.getUserInfo();
        Role role = loUsRo.getRole();
        // 检查账户是否存在
        QueryWrapper<Login> loginQw = new QueryWrapper<>();
        loginQw.eq("user_account", login.getUserAccount());
        List<Login> logins = loginMapper.selectList(loginQw);
        if (!logins.isEmpty()){
            return new ResponseResult<>(400, "该账户已存在");
        }

        // 检查员工是否存在
        QueryWrapper<UserInfo> userQw = new QueryWrapper<>();
        userQw.eq("user_name", userInfo.getUserName());
        List<UserInfo> userInfos = userInfoMapper.selectList(userQw);
        if (userInfos.isEmpty()){
            return new ResponseResult<>(400, "不存在该员工");
        }
        login.setUserNo(userInfos.get(0).getUserInfoId());

        // 检查角色是否存在
        QueryWrapper<Role> roleQw = new QueryWrapper<>();
        roleQw.eq("role_name", role.getRoleName());
        List<Role> roles = roleMapper.selectList(roleQw);
        if (roles.isEmpty()){
            return new ResponseResult<>(400, "不存在该角色");
        }
        login.setUserRoleId(roles.get(0).getRoleId());
        login.setUserName(userInfos.get(0).getUserName());
        login.setUserError(0);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        login.setUserCreateTime(format.format(new Date()));

        // 密码加密
        String salt = RandomStringUtils.randomAlphabetic(10);
        int saltIndex = (int) (Math.random() * 10);
        login.setUserSalt(salt);
        login.setUserIndex(saltIndex);
        login.setUserPwd(MD5Util.md5To32String(login.getUserPwd(), salt, saltIndex));

        if (loginMapper.insert(login) > 0){
            return new ResponseResult<>();
        }

        return new ResponseResult<>(400, "添加失败");
    }

    /**
     * 修改账户信息
     */
    @Override
    public ResponseResult<Object> editLogin(LoUsRo loUsRo) {
        Login login = loUsRo.getLogin();
        UserInfo userInfo = loUsRo.getUserInfo();
        Role role = loUsRo.getRole();

        // 检查员工是否存在
        QueryWrapper<UserInfo> userQw = new QueryWrapper<>();
        userQw.eq("user_name", userInfo.getUserName());
        List<UserInfo> userInfos = userInfoMapper.selectList(userQw);
        if (userInfos.isEmpty()){
            return new ResponseResult<>(400, "不存在该员工");
        }
        login.setUserNo(userInfos.get(0).getUserInfoId());

        // 检查角色是否存在
        QueryWrapper<Role> roleQw = new QueryWrapper<>();
        roleQw.eq("role_name", role.getRoleName());
        List<Role> roles = roleMapper.selectList(roleQw);
        if (roles.isEmpty()){
            return new ResponseResult<>(400, "不存在该角色");
        }
        login.setUserRoleId(roles.get(0).getRoleId());
        login.setUserName(userInfos.get(0).getUserName());
        login.setUserError(0);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        login.setUserCreateTime(format.format(new Date()));

        if (!"".equals(login.getUserPwd()) && login.getUserPwd() != null){
            String salt = RandomStringUtils.randomAlphabetic(10);
            int saltIndex = (int) (Math.random() * 10);
            login.setUserSalt(salt);
            login.setUserIndex(saltIndex);
            login.setUserPwd(MD5Util.md5To32String(login.getUserPwd(), salt, saltIndex));
        } else {
            // 密码不修改
            QueryWrapper<Login> loginQw = new QueryWrapper<>();
            loginQw.eq("user_account", login.getUserAccount());
            List<Login> logins = loginMapper.selectList(loginQw);
            if (logins.isEmpty()){
                return new ResponseResult<>(400, "该账号不存在");
            }
            login.setUserPwd(logins.get(0).getUserPwd());
        }

        if (loginMapper.updateById(login) > 0){
            return new ResponseResult<>();
        }
        return new ResponseResult<>(400, "修改失败");
    }
}




